package com.mb.demo.controller;/*
 @author mabin
 @DESCRIPTION 
 @create 2023-5-19
*/

import com.mb.demo.entity.User;
import com.mb.demo.service.UserService;
import com.mb.demo.vo.UserVo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class UserController {

    @Resource
    private UserService userService;

    @RequestMapping("/user/getAll")
//    @ResponseBody
    public String getAll(Model model){

        List<User> users = userService.getAll();
        model.addAttribute("users",users);
        return "users";
    }

    //produces = "application/json; charset=utf-8" 解决中文乱码问题
    @RequestMapping(value ="/user/getById/{id}",produces = "application/json; charset=utf-8")
    @ResponseBody
    public User getById(@PathVariable String id){
        User user = userService.getById(id);
        System.out.println(user);
        return user;
    }

    /**
     * 使用JSR303进行校验
     * @param userVo
     * @param bindingResult
     * @return
     */
    @PostMapping("/user/saveUser")
    @ResponseBody
    public Object saveUser(@RequestBody @Valid UserVo userVo, BindingResult bindingResult){

        if (bindingResult.hasErrors()){ //如果有错误会进入到以下逻辑
            return this.bindingResultOutput(bindingResult);
        }else { //没有发生错误，走逻辑代码
            userService.saveUser(userVo);
            return "添加成功";
        }
    }

    private Map<String, String> bindingResultOutput( BindingResult bindingResult){
        Map<String, String> map = new HashMap<>(); //用来存放所有信息数据
        bindingResult.getFieldErrors().forEach(item->{
            String field = item.getField(); //取出发生错误的字段
            String defaultMessage = item.getDefaultMessage(); //取出字段对应的提示信息
            map.put(field,defaultMessage);
        });
        return map;
    }



}
